/**
 * @description 用户 services
 */
const _ = require('lodash')
const User = require('../db/model/User')
const Member = require('../db/model/Member')
const doCrypto = require('../utils/crypto')

// 初始化注册用户，会创建一些初始数据
function _getToBeCreatedUser(account, password) {
  const toBeCreatedFields = {
    account,
    password: doCrypto(password),
    nickName: `用户${account.slice(-4)}` // 初始昵称
  }
  return toBeCreatedFields
}

/**
 * 获取用户信息
 * @param {object} param0 查询条件 { id, account, password }
 * @returns null | 用户数据
 */
async function getUserInfo({ id, account, password }) {
  // 查询条件过滤
  const whereOpt = {}
  if (!_.isUndefined(id)) { whereOpt.id = id }
  if (!_.isUndefined(account)) { whereOpt.account = account }
  if (!_.isUndefined(password)) { whereOpt.password = password }

  const userInfo = await User.findOne({
    attributes: ['id', 'account', 'password', 'nickName', 'gender', 'birthday', 'imgUrl', 'provinceId',
      'cityId', 'sign'],
    where: whereOpt,
    raw: true,
    include: { // 关联查询会员表
      model: Member,
      attributes: ['id', 'lastClockDate', 'clockCount'],
      required: false,
    }
  })

  return userInfo
}

/**
 * 创建 1 个用户
 * @param {string} account 账号
 * @param {string} password 密码
 */
async function createUserInst(account, password) {
  const userInst = await User.create(_getToBeCreatedUser(account, password));
  return userInst;
}

/**
 * 更新个人基本信息
 * @param {object} toUpdate 要更新的老师基本信息 { role, name, gender, portraitUrl }
 * @param {object} { id, password } 查询条件
 * @returns {boolean} true - 更新成功，false - 更新失败
 */
async function updateBasicInfo(toUpdate, { id, password }, needCheck = true) {
  // 构造查询条件
  const whereOpt = {}
  if (_.isNumber(id)) { whereOpt.id = id }
  if (!_.isEmpty(password)) { whereOpt.password = password }

  const result = await User.update(toUpdate, {
    where: whereOpt
  })
  return result[0] === 1 // 通过判断更新行数来判断操作成功与否
}

module.exports = {
  getUserInfo,
  createUserInst,
  updateBasicInfo,
}
